<?php

namespace Apps\AppApi\Method\Question;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\Question;
use Apps\Common\Models\QuestionFollow;
use PhalconPlus\Api\Common\ResultStatus;


/**
 * 关注问题
 * @package Apps\AppApi\Method\Follow
 */
class Follow extends BaseMethod
{
    /**
     * @var int
     */
    private $success = 0;

    public function run()
    {
        /**
         * 验证用户权限
         */
        if(false == $this->verifyUserAuth()){
            return false;
        }
        $user = $this->getUserAuth();

        /**
         * 获取关注次数
         */
        $questionId = intval($this->getDataItem('question_id',0));

        if($questionId <= 0) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "问题ID必须大于0.");
        }
        $follow = QuestionFollow::count([
            "conditions"=>"user_id = :uid: AND question_id = :qid: ",
            "bind" => [
                'uid' => $user->userId,
                'qid' => $questionId,
            ],
        ]);

        /**
         * 有权限且未关注则执行关注
         */
        if($follow == 0) {
            $qf = new QuestionFollow();
            $qf->user_id = $user->userId;
            $qf->question_id = $questionId;
            if($qf->save()) {
                $this->success = 1;
            } else {
                return $this->databaseErrorLog($qf);
            }
            $this->setResult(["success" => $this->success, 'message' => '收藏成功']);
        } else {
            $this->success = 2;
            $this->setResult(["success" => $this->success, 'message' => '已收藏']);
        }


    }

}